/**
 * @desc   判断平台类型
 * @return {string} 如iphone或者gphone
 */
export const getPlatform = () => {
  if (/iphone|mac|ipad/i.test(navigator.userAgent)) {
    return 'iphone';
  } else {
    return 'gphone';
  }
};

/**
 * @desc   判断安卓系统版本号
 * @return {string} 如4.3.2或者9.0
 */
export function getGphoneVersion() {
  // 获取ua信息并且转化为小写
  const ua = navigator.userAgent.toLowerCase();
  // 声明系统版本
  let version = null;

  if (ua.indexOf('android') >= 0) {
    const reg = /android [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @desc   判断苹果系统版本号
 * @return {string} 如9.3.2或者9.0
 */
export function getIphoneVersion() {
  // 获取ua信息并且转化为小写
  const ua = navigator.userAgent.toLowerCase();
  // 声明系统版本
  let version = null;

  if (ua.indexOf('like mac os x') >= 0) {
    const reg = /os [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @desc 获取页面中的参数，#/后面的无法获取
 * @param name 指定参数key
 * @return
 */
export function getParam(name?: string) {
  const search = location.href.substring(location.href.indexOf('?') + 1).replace(/#\/|\?/gi, '&');
  const resObj: Record<string, string | undefined> = {};

  search.split('&').forEach(item => {
    const arr = item.split('=');
    if (arr[1]) {
      resObj[arr[0]] = arr[1];
    }
  });

  if (name === undefined) {
    return resObj;
  }

  return resObj[name] || '';
}

/**
 * @description: 动态加载 js 脚本文件
 * @param {string} url
 */
export function loadJs(url: string) {
  return new Promise<void>((resolve, reject) => {
    const head = document.getElementsByTagName('head')[0];
    const jsNode = document.createElement('script');
    jsNode.setAttribute('type', 'text/javascript');
    jsNode.setAttribute('src', url);

    jsNode.onload = function () {
      resolve();
    };

    jsNode.onerror = function () {
      reject(new Error(`Failed to load script ${url}`));
    };

    head.appendChild(jsNode);
  });
}

/**
 * @description: 动态支持 js 代码段
 * @param {string} url
 */
export function evalJs(jsInput: string) {
  let ret;
  try {
    ret = eval.call(window, `(${jsInput})`);
  } catch (e) {
    ret = eval.call(window, jsInput);
  }
  return ret;
}

/**
 * @description: 处理客户端响应数据
 * @param val 
 * @returns 
 */
export function getFormattedRes(val: unknown) {
  if (typeof val === 'string' && val[0] === '{') {
    try {
      return JSON.parse(val);
    } catch (err) {
      return val;
    }
  }
  return val;
}
